<?php
namespace User\Model;
use Zend\Db\TableGateway\TableGateway;
use User\Model\Entity\User;

class UserTable {
	
	protected $tableGateway;
	
	/**
	 * @return the $tableGateway
	 */
	public function getTableGateway() {
		return $this->tableGateway;
	}

	/**
	 * @param TableGateway $tableGateway
	 */
	public function setTableGateway($tableGateway) {
		$this->tableGateway = $tableGateway;
	}

	public function __construct(TableGateway $tableGateway)
	{
		$this->tableGateway = $tableGateway;
	}
	
	public function fetchAll()
	{
		$resultSet = $this->tableGateway->select();
		
		return $resultSet;
	}
        
                
	public function getUser($id)
	{
		$id = (int) $id;
		
		$rowset = $this->tableGateway->select(array('id' => $id));
		
		$row = $rowset->current();
		
		if (!$row) {
			
			throw new \Exception("Could not find row $id");
			
		}
		
		return $row;
	}
	public function saveUser(User $user)
	{
		$data = array(
				'username' => $user->getUsername(),
				'password' => $user->getPassword(),
				'first_name' => $user->getFirst_name(),
				'middle_name' => $user->getMiddle_name(),
				'last_name' => $user->getLast_name(),
				'dob' => $user->getDob(),
				'avatar' => $user->getAvatar(),
				'phone' => $user->getPhone(),
				'email' => $user->getEmail(),
				'state' => $user->getState(),
		);
		
		if($data['state'] == null)
		{
			unset($data['state']);
		}
		
		$id = (int)$user->getId();
		
		if ($id == 0) {
			
			$this->tableGateway->insert($data);
			
		} else {
			
			if ($this->getUser($id)) {
				
				$this->tableGateway->update($data, array('id' => $id));
				
			} else {
				
				throw new \Exception('Form id does not exist');
				
			}
		}
	}
	public function deleteUser($id)
	{
		$this->tableGateway->delete(array('id' => $id));
	}
        
        public function changePassword($uid, $newPass)
        {
            $this->tableGateway->update(array('password' => $newPass), array('id' => $uid));
        }
}
